package com.lanlian.cayman.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.bean.db.DBMarketS;
import com.lanlian.commonlib.data.ContractBean;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.KLineActivity;
import com.lanlian.cayman.adapter.NewMarketAdapter;
import com.lanlian.cayman.bean.EventZixuanData;
import com.lanlian.cayman.bean.MyContractBean;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;
import com.oms.rpc.protobuf.TickHqResp;
import com.oms.rpc.protobuf.YsHqInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/9/13 15:35
 *     desc   : todo
 *     version: 1.0
 * </pre>
 */
public class MarketInfoFragment extends BaseFragment {

    private ListView mRecyclerView;
    private NewMarketAdapter adapter;
    private String id;
    private ArrayList<MyContractBean> myContractBeans = new ArrayList<>();

    private boolean mIsVisibleToUser;
    private boolean mIsParentVisibleToUser = true;
    private boolean mIsScrolling;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisibleToUser = isVisibleToUser;
        if (mIsVisibleToUser) {
            getTickHq();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsVisibleToUser) {
            getTickHq();
        }
    }

    public void setIsParentVisibleToUser(boolean isParentVisibleToUser) {
        this.mIsParentVisibleToUser = isParentVisibleToUser;
    }

    public MarketInfoFragment getInstance(String id) {
        MarketInfoFragment fragment = new MarketInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_market, null);
        initView(view);
        initData();
        initAdapter();
        return view;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mRecyclerView = view.findViewById(R.id.recycle_view);
    }

    @Override
    protected void initData() {
        super.initData();
        id = getArguments().getString("id");
    }

    private void initAdapter() {
        myContractBeans = selectMarketItem(id, MarketFragment.getRespMarket().getContractList());
        adapter = new NewMarketAdapter(getActivity(), myContractBeans, new NewMarketAdapter.OnClickListener() {
            @Override
            public void onClick(MyContractBean contractBean, ImageView imageView) {
                if (isZiXuan(contractBean.id)) {
                    mDBManager.deleteMarketS(contractBean.id);
                    imageView.setImageResource(R.mipmap.quotation_icon_addto);
                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH, new EventZixuanData(contractBean, false)));
                } else {
                    DBMarketS ms = new DBMarketS();
                    ms.setId(contractBean.id);
                    ms.setName(contractBean.name);
                    mDBManager.setMarketS(ms);
                    imageView.setImageResource(R.mipmap.quotation_icon_cutdown);
                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH, new EventZixuanData(contractBean, true)));
                }
            }
        });
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OnEventUtils.onEvent(getActivity(), OnEventID.CONTRACT,
                        myContractBeans.get(position).name + myContractBeans.get(position).id);
                Intent intent = new Intent();
                intent.setClass(getActivity(), KLineActivity.class);
                intent.putExtra("name", myContractBeans.get(position).name);
                intent.putExtra("id", myContractBeans.get(position).id);
                startActivity(intent);
            }
        });
        mRecyclerView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_IDLE:
                        //滑动停止时调用
                        mIsScrolling = false;
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        //正在滚动时调用
                        mIsScrolling = true;
                        break;
                    case SCROLL_STATE_FLING:
                        //手指快速滑动时,在离开ListView由于惯性滑动
                        mIsScrolling = true;
                        break;
                    default:
                        mIsScrolling = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

//        adapter = new MarketAdapter(R.layout.fragment_market_item, myContractBeans);
//        mRecyclerView.setAdapter(adapter);
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        adapter.bindToRecyclerView(mRecyclerView);
//        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
//            @Override
//            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Intent intent = new Intent();
//                intent.setClass(getActivity(), KLineActivity.class);
//                intent.putExtra("name", myContractBeans.get(position).name);
//                intent.putExtra("id", myContractBeans.get(position).id);
//                startActivity(intent);
//            }
//        });
//        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                MyContractBean contractBean = myContractBeans.get(position);
//                if (isZiXuan(contractBean.id)) {
//                    mDBManager.deleteMarketS(contractBean.id);
//                    ((ImageView) adapter.getViewByPosition(position, R.id.iv)).setImageResource(R.mipmap.quotation_icon_addto);
//                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH, new EventZixuanData(contractBean, false)));
//                } else {
//                    DBMarketS ms = new DBMarketS();
//                    ms.setId(contractBean.id);
//                    ms.setName(contractBean.name);
//                    mDBManager.setMarketS(ms);
//                    ((ImageView) adapter.getViewByPosition(position, R.id.iv)).setImageResource(R.mipmap.quotation_icon_cutdown);
//                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH, new EventZixuanData(contractBean, true)));
//                }
//            }
//        });
    }

    private ArrayList<MyContractBean> selectMarketItem(String id, ArrayList<ContractBean> list) {
        ArrayList<MyContractBean> select = new ArrayList<>();
        if ("-2".equals(id)) {
            for (ContractBean bean : list) {
                MyContractBean contractBean = new MyContractBean();
                contractBean.id = bean.contractNo;
                contractBean.name = bean.contractName;
                select.add(contractBean);
            }
        } else if ("-1".equals(id)) {
            for (ContractBean bean : list) {
                if (isZiXuan(bean.contractNo)) {
                    MyContractBean contractBean = new MyContractBean();
                    contractBean.id = bean.contractNo;
                    contractBean.name = bean.contractName;
                    select.add(contractBean);
                }
            }
        } else {
            for (ContractBean bean : list) {
                if (id.equals(bean.marketId)) {
                    MyContractBean contractBean = new MyContractBean();
                    contractBean.id = bean.contractNo;
                    contractBean.name = bean.contractName;
                    select.add(contractBean);
                }
            }
        }
        return select;
    }

    public void updateAdapter(HqMsg.YsHqInfo ysHqInfo) {
        for (MyContractBean myContractBean : myContractBeans) {
            if (myContractBean.id.equals(ysHqInfo.getCommodityNo() + ysHqInfo.getContractNo1())) {
                myContractBean.open = ysHqInfo.getQOpeningPrice() + "";
                myContractBean.last = ysHqInfo.getQLastPrice() + "";
                myContractBean.chg = ysHqInfo.getQChangeRate() + "";
                myContractBean.change = ysHqInfo.getQChangeValue() + "";
                adapter.notifyDataSetChanged(mRecyclerView, myContractBeans.indexOf(myContractBean));
                break;
            }
        }
    }

    public void updateZixuan(MyContractBean myContractBean, boolean isAdd) {
        if ("-1".equals(id)) {
            if (isAdd) {
                myContractBeans.add(myContractBean);
                adapter.notifyDataSetChanged();
            } else {
                for (MyContractBean contractBean : myContractBeans) {
                    if (contractBean.id.equals(myContractBean.id)) {
                        int position = myContractBeans.indexOf(contractBean);
                        myContractBeans.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        } else {
            for (MyContractBean contractBean : myContractBeans) {
                if (contractBean.id.equals(myContractBean.id)) {
                    adapter.notifyDataSetChanged(mRecyclerView, myContractBeans.indexOf(contractBean));
                    break;
                }
            }
        }
    }

    private boolean isZiXuan(String id) {
        List<DBMarketS> list = mDBManager.getMarketS();
        if (list != null) {
            for (DBMarketS dbMarketS : list) {
                if (id.equals(dbMarketS.getId())) {
                    return true;
                }
            }
        }
        return false;
    }

    private void setMarket(HqMsg.YsHqInfo ysHqInfo) {
        if (ysHqInfo == null) {
            return;
        }
        if (mIsVisibleToUser && isResumed() && mIsParentVisibleToUser && !mIsScrolling) {
            updateAdapter(ysHqInfo);
        }
    }

    private void getTickHq() {
        ProtoManager pm = new ProtoManager();
        OMSTradeReq.Builder oms = pm.getRequst(6);
        OMSTradeReq om = oms.build();
        SocketCallImpl socketCall = new SocketCallImpl((BaseActivity) getActivity()) {
            @Override
            public void error(Exception e) {
            }

            @Override
            public void message(byte[] data) {
                try {
                    OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                    TickHqResp tickHqResp = oms.getTickhqResp();
                    if (tickHqResp != null) {
                        setData(tickHqResp);
                    }
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            }
        };
        MySocketManager ms = new MySocketManager();
        ms.setCongLian(true);
        ms.sendData(om.toByteArray(), socketCall);
    }

    private void setData(TickHqResp tickHqResp) {
        for (YsHqInfo ysHqInfo : tickHqResp.getTickhqinfoList()) {
            updateAdapter(exchangeData(ysHqInfo));
        }
    }

    private HqMsg.YsHqInfo exchangeData(YsHqInfo ysHqInfo) {
        HqMsg.YsHqInfo.Builder builder = HqMsg.YsHqInfo.newBuilder();
        builder.setCommodityNo(ysHqInfo.getCommodityNo());
        builder.setContractNo1(ysHqInfo.getContractNo1());
        builder.setQOpeningPrice(ysHqInfo.getQOpeningPrice());
        builder.setQLastPrice(ysHqInfo.getQLastPrice());
        builder.setQChangeRate(ysHqInfo.getQChangeRate());
        builder.setQChangeValue(ysHqInfo.getQChangeValue());
        return builder.build();
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_ZIXUAN_REFRESH:
                EventZixuanData eventZixuanData = (EventZixuanData) event.getData();
                if (eventZixuanData.isAdd()) {
                    OnEventUtils.onEvent(getActivity(), OnEventID.CONTRACT_ADD);
                } else {
                    OnEventUtils.onEvent(getActivity(), OnEventID.CONTRACT_DELETE);
                }
                 updateZixuan(eventZixuanData.getContractBean(), eventZixuanData.isAdd());
                break;
            case EventCode.EVENT_MARKET:
                HqMsg.YsHqInfo ysHqInfo = (HqMsg.YsHqInfo) event.getData();
                setMarket(ysHqInfo);
                break;
            case EventCode.EVENT_MARKET_COLOR_CHANGE:
                adapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

}
